package com.hsy.linemoney.modules.home;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPUnitUtil;
import com.deparse.dpframe.ui.android.widget.DPViewPager;
import com.deparse.dpframe.ui.android.widget.DPagerSlidingTabStrip;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.CalculateService;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.CurrencyService;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.hsy.linemoney.apiservice.ServiceTypeService;
import com.hsy.linemoney.modules.common.CommonBaseFragment;
import com.hsy.linemoney.modules.main.MainActivity;
import com.hsy.linemoney.utils.CommonUtils;

/**
 * Created by Administrator on 2016/6/23.
 */
public class HomeFragment extends CommonBaseFragment {

    private static final int MSG_CALCULATE = 0x5001;
    private DPViewPager activity_repair_viewpager;
    private DPagerSlidingTabStrip tabs;
    private MyPagerAdapter adapter;

    private TextView next_text;

    private TextView rate_result;
    private EditText user_input;

    private boolean isInited = false;

    private CalculateService calculateService = new CalculateService();

    private DPViewPager.OnPageChangeListener onPageChangeListener = new DPViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int position) {
            if (isInited) {
                ViewGroup tabContainer = (ViewGroup) tabs.getChildAt(0);
                for (int i = 0; i < tabContainer.getChildCount(); i++) {
                    TextView child = (TextView) tabContainer.getChildAt(i);
                    child.setTextColor(getResources().getColor(i == position ? R.color.common_green : R.color.tab_text_color_normal));
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    };
    private TextView left_spinner;
    private TextView right_spinner;
    private CurrencyService.CurrencyListResult mCurrencyListResult;
    private int leftWitch = -1, rightWitch = -1;
    private View space_area;

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_home;
    }

    private View.OnTouchListener mLooseFocuseListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEvent.ACTION_DOWN == event.getAction()) {
                user_input.clearFocus();
                user_input.setFocusable(false);
                user_input.setFocusableInTouchMode(true);
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(user_input.getWindowToken(), 0);

                calculate();
                return true;
            }
            return false;
        }
    };

    private CurrencyService currencyService = new CurrencyService();
    private ServiceTypeService serviceTypeService = new ServiceTypeService();

    @Override
    public void onDestroy() {
        super.onDestroy();
        currencyService.cancel();
        serviceTypeService.cancel();
    }

    private FragmentHomeRateCheckView rateCheckView;

    private void calculate() {
        showProgressDialog(getAttchedActivity());
        if (TextUtils.isEmpty(user_input.getText().toString())) {
            rate_result.setText("0.00");
            hideProgressDialog();
        } else {
            if (null == getAttchedActivity() || getAttchedActivity().isFinishing() || getAttchedActivity().isDestroyed()) {
                hideProgressDialog();
                return;
            }
            String source, target;
            if (isSwitched()) {
                source = mCurrencyListResult.getCurrency().get(rightWitch).getCurrencyCd();
                target = mCurrencyListResult.getCurrency().get(leftWitch).getCurrencyCd();
            } else {
                source = mCurrencyListResult.getCurrency().get(leftWitch).getCurrencyCd();
                target = mCurrencyListResult.getCurrency().get(rightWitch).getCurrencyCd();
            }
            final String send = TextUtils.isEmpty(user_input.getText().toString()) ? "0" : user_input.getText().toString();
            calculateService.calculate(source, target, send, "0", "ServiceType_101", "0", new Callback<CalculateService.CalculateResult>() {
                @Override
                public void onSuccess(int what, CalculateService.CalculateResult result) {
                    double amount = Double.valueOf(send);
                    double rate = Double.valueOf(result.getData().getLmData().getLinemoneyRate());
                    double fee = Double.valueOf(result.getData().getLmData().getLinemoneyTransferFee());
                    rate_result.setText(String.format(LineMoneyContext.getLocalLanguagePair().locale, "%.2f", Double.valueOf(result.getData().getLmData().getLinemoneyPayOut())));
                    hideProgressDialog();
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {
                    hideProgressDialog();
                }
            });
        }
    }

    @Override
    protected void initView(final View view, Bundle savedInstanceState) {
//        showProgressDialog(getAttchedActivity());

        rateCheckView = F(R.id.rate_calc_layout);
        rateCheckView.setAnimationListener(new FragmentHomeRateCheckView.AnimationListener() {
            @Override
            public void onAnimationStart() {
                rateCheckView.setEnabled(false);
                calculateService.cancel();
                removeMessages(MSG_CALCULATE);
                leftWitch = leftWitch + rightWitch;
                rightWitch = leftWitch - rightWitch;
                leftWitch = leftWitch - rightWitch;
                sendEmptyMessageDelayed(MSG_CALCULATE, 500);
            }

            @Override
            public void onAnimationEnd() {
                rateCheckView.setEnabled(true);
            }
        });

        left_spinner = F(R.id.left_spinner);
        right_spinner = F(R.id.right_spinner);

        next_text = F(R.id.commit);
        next_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!LineMoneyContext.isLoggedIn()) {
                    ((MainActivity) getAttchedActivity()).showLoginDialog();
                    return;
                }
                if (isSwitched()) {
                    ((MainActivity) getAttchedActivity()).setExchangeWay(rightWitch, leftWitch);
                } else {
                    ((MainActivity) getAttchedActivity()).setExchangeWay(leftWitch, rightWitch);
                }
                ((MainActivity) getAttchedActivity()).setExchangeAmount(user_input.getText().toString());
                ((MainActivity) getAttchedActivity()).setCurrentTab(1);
            }
        });

        activity_repair_viewpager = F(R.id.activity_repair_viewpager);

        tabs = F(R.id.tabs);

        tabs.setOnPageChangeListener(onPageChangeListener);

        rate_result = F(R.id.rate_result);
        user_input = F(R.id.user_input);

        space_area = F(R.id.space_area);

        user_input.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                user_input.performClick();
                return true;
            }
        });

        user_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                removeMessages(MSG_CALCULATE);
                sendEmptyMessageDelayed(MSG_CALCULATE, 500);
            }
        });

        space_area.setOnTouchListener(mLooseFocuseListener);
        ((View) F(R.id.rate_calc_layout)).setOnTouchListener(mLooseFocuseListener);
        ((View) F(R.id.layout_1)).setOnTouchListener(mLooseFocuseListener);
//        ((View) F(R.id.layout_2)).setOnTouchListener(mLooseFocuseListener);
        ((View) F(R.id.layout_3)).setOnTouchListener(mLooseFocuseListener);
        ((View) F(R.id.layout_4)).setOnTouchListener(mLooseFocuseListener);
        ((View) F(R.id.layout_5)).setOnTouchListener(mLooseFocuseListener);
        ((View) F(R.id.tabs)).setOnTouchListener(mLooseFocuseListener);
        ((View) F(R.id.activity_repair_viewpager)).setOnTouchListener(mLooseFocuseListener);

        left_spinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLeftDialog();
            }
        });
        right_spinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showrightDialog();
            }
        });

        currencyService.getCurrency(currencyCallback);
    }

    private Callback<CurrencyService.CurrencyListResult> currencyCallback = new Callback<CurrencyService.CurrencyListResult>() {
        @Override
        public void onSuccess(int what, CurrencyService.CurrencyListResult result) {
            if (null != getAttchedActivity() && !getAttchedActivity().isDestroyed() && !getAttchedActivity().isFinishing()) {
                HomeFragment.this.mCurrencyListResult = result;
                if (mCurrencyListResult.getCurrency().size() > 1) {
                    leftWitch = 1;
                    rightWitch = 0;
                    left_spinner.setText(getCurrency(leftWitch).getDescription());
                    right_spinner.setText(getCurrency(rightWitch).getDescription());
                }
                serviceTypeService.getServiceTypeList(serviceTypeListResultCallback);
                calculate();
            }
        }

        @Override
        public void onError(int what, int type, String msg, Exception e) {
            showToast(msg);
            hideProgressDialog();
        }
    };

    private Callback<ServiceTypeService.ServiceTypeListResult> serviceTypeListResultCallback = new Callback<ServiceTypeService.ServiceTypeListResult>() {
        @Override
        public void onSuccess(int what, ServiceTypeService.ServiceTypeListResult result) {
            if (null != getAttchedActivity() && !getAttchedActivity().isDestroyed() && !getAttchedActivity().isFinishing()) {
                showTab(result.getPages());
                next_text.setEnabled(true);
                isInited = true;
                onPageChangeListener.onPageSelected(0);
            }
            hideProgressDialog();
        }

        @Override
        public void onError(int what, int type, String msg, Exception e) {
            hideProgressDialog();
        }
    };

    private String[] currencyArray;

    public String[] getCurrencyArray() {
        if (null == mCurrencyListResult) {
            return null;
        }
        if (null == currencyArray) {
            currencyArray = new String[mCurrencyListResult.getCurrency().size()];
            for (int i = 0; i < currencyArray.length; i++) {
                currencyArray[i] = mCurrencyListResult.getCurrency().get(i).getDescription();
            }
        }
        return currencyArray;
    }

    public CurrencyService.CurrencyListResult.Currency getCurrency(int which) {
        if (null == mCurrencyListResult) {
            return null;
        }
        return mCurrencyListResult.getCurrency().get(which);
    }

    private void showLeftDialog() {
        CommonUtils.showListDialog(getAttchedActivity(), getCurrencyArray(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                leftWitch = which;
                left_spinner.setText(getCurrencyArray()[which]);
                rightWitch = 1 - which;
                right_spinner.setText(getCurrencyArray()[1 - which]);
                calculate();
                dialog.dismiss();
            }
        });
    }

    private void showrightDialog() {
        CommonUtils.showListDialog(getAttchedActivity(), getCurrencyArray(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                rightWitch = which;
                right_spinner.setText(getCurrencyArray()[which]);
                leftWitch = 1 - which;
                left_spinner.setText(getCurrencyArray()[1 - which]);
                calculate();
                dialog.dismiss();
            }
        });
    }

    private boolean isSwitched = false;

    /**
     * 判断左右位置是否交换过，提交数据时会用到
     *
     * @return
     */
    private boolean isSwitched() {
        return isSwitched;
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message msg) {
        if (MSG_CALCULATE == msg.what) {
            removeMessages(MSG_CALCULATE);
            calculate();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onFragmentUpdate() {
    }


    private void showTab(ServiceTypeService.ServiceTypeListResult.Pages data) {

        adapter = new MyPagerAdapter(getChildFragmentManager(), data);

        tabs.setIndicatorHeight(2);
        tabs.setIndicatorWidth(DPUnitUtil.dip2px(getAttchedActivity(), 50));
        tabs.setUnderlineColor(getResources().getColor(R.color.line));

        int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
        activity_repair_viewpager.setAdapter(adapter);
        activity_repair_viewpager.setPageMargin(pageMargin);
        tabs.setViewPager(activity_repair_viewpager);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

        private ServiceTypeService.ServiceTypeListResult.Pages pages;

        public MyPagerAdapter(FragmentManager fragmentmanager, ServiceTypeService.ServiceTypeListResult.Pages pages) {
            super(fragmentmanager);
            this.pages = pages;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "≥" + pages.getNames().get(position);
        }

        @Override
        public Fragment getItem(int position) {
            ServiceTypeListFragment fragment = new ServiceTypeListFragment();
            fragment.setData(pages.getPageAt(position));
            return fragment;
        }

        @Override
        public int getCount() {
            return pages.size();
        }
    }
}
